package com.sky.controller.user;

import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("新增地址:{}", addressBook);
        addressBookService.save(addressBook);
        return Result.success();
    }

    /**
     * 查询用户地址
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> list() {
        log.info("查询用户地址");
        List<AddressBook> addressBookList = addressBookService.list();
        return Result.success(addressBookList);
    }

    /**
     * 查询默认地址
     *
     * @return
     */
    @GetMapping("/default")
    public Result getAddressBook(AddressBook addressBook) {
        log.info("查询默认地址:{}", addressBook);
        AddressBook defaultAddressBook = addressBookService.getAddressBook(addressBook);
        if (defaultAddressBook != null) {
            return Result.success(defaultAddressBook);
        } else {
            return Result.error("没有查询到默认地址");
        }
    }

    @PutMapping("/default")
    public Result setAddressBook(@RequestBody AddressBook addressBook) {
        log.info("修改默认地址:{}", addressBook);
        addressBookService.setAddressBook(addressBook);

        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<AddressBook> selectById(@PathVariable Long id) {
        log.info("根据id查询地址:{}", id);
        AddressBook addressBook = addressBookService.selectById(id);
        return Result.success(addressBook);
    }

    /**
     * 根据id修改地址簿信息
     */
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        log.info("根据id修改地址:{}", addressBook);
        addressBookService.update(addressBook);
        return Result.success();
    }

    @DeleteMapping
    public Result deleteById(Long id) {
        log.info("根据id删除地址:{}", id);
        addressBookService.deleteById(id);
        return Result.success();
    }
}
